import { Injectable, Inject } from '@nestjs/common';
import Redis from 'ioredis';
import { REDIS_KEYS, REDIS_EXPIRE } from './redis.config';

@Injectable()
export class RedisService {
  constructor(@Inject('REDIS_CLIENT') private readonly redis: Redis) {}

  // 设置带过期时间的键值对
  async setex(key: string, seconds: number, value: string): Promise<void> {
    await this.redis.setex(key, seconds, value);
  }

  // 获取值
  async get(key: string): Promise<string | null> {
    return await this.redis.get(key);
  }

  // 删除键
  async del(key: string): Promise<number> {
    return await this.redis.del(key);
  }

  // 增加计数器
  async incr(key: string): Promise<number> {
    return await this.redis.incr(key);
  }

  // 设置过期时间
  async expire(key: string, seconds: number): Promise<number> {
    return await this.redis.expire(key, seconds);
  }

  // 检查键是否存在
  async exists(key: string): Promise<number> {
    return await this.redis.exists(key);
  }

  // 获取键的剩余过期时间
  async ttl(key: string): Promise<number> {
    return await this.redis.ttl(key);
  }

  // 原子操作：设置值并返回旧值
  async getset(key: string, value: string): Promise<string | null> {
    return await this.redis.getset(key, value);
  }

  // 批量删除匹配的键
  async delPattern(pattern: string): Promise<void> {
    const keys = await this.redis.keys(pattern);
    if (keys.length > 0) {
      await this.redis.del(...keys);
    }
  }

  // 获取 Redis 连接状态
  async ping(): Promise<string> {
    return await this.redis.ping();
  }

  // 获取 Redis 信息
  async info(): Promise<string> {
    return await this.redis.info();
  }
} 